/* 
   用户登陆信息
*/
const { log } = require('debug/src/browser');
var express = require('express');
var query = require('../connent/mysqlPool') // 引入数据库连接池文件
let format = require('./format');
var router = express.Router();


/* 添加登陆信息 */
router.get('/updatelogininfo', (req, res) => {
  let id = req.query.id
  let ip = req.query.ip
  let searchLoginInfo = "select * from user_login_info where user_id=?"
  let addLoginInfo = "insert into user_login_info values(?,?,?,?,?)"
  let updateLoginInfo = "update user_login_info set ? where user_id=?"
  query(searchLoginInfo, [id], (err, result, fields) => {
    if(result.length===0){ //从未登陆
      query(addLoginInfo, [id,ip,1,new Date(),new Date()], (err, result, fields) => {})
    }else{
      /* 更新登陆次数和当前时间 */
      let logininfo = result[0]
      logininfo.login_count = logininfo.login_count +1
      logininfo.current_time = new Date()
      query(updateLoginInfo, [logininfo, logininfo.user_id], (err, result, fields) => {})
    }
  })
})


/* 更新上次登陆信息 */
router.get('/updatelogin', (req, res) => {
  let id = req.query.id
  let searchLoginInfo = "select * from user_login_info where user_id=?"
  let updateLoginInfo = "update user_login_info set ? where user_id=?"
  query(searchLoginInfo, [id], (err, result, fields) => {
    /* 将此次登陆的时间作为下此登陆时，显示的上次登陆时间的值 */
    let logininfo = result[0]
    logininfo.login_time = logininfo.current_time
    console.log(logininfo);
    query(updateLoginInfo, [logininfo, logininfo.user_id], (err, result, fields) => { })
  })
})


/* 获取登陆信息 */
router.get('/getlogininfo', (req, res) => {
  let id = req.query.id
  let searchLoginInfo = "select * from user_login_info where user_id=?"
  query(searchLoginInfo, [id], (err, result, fields) => {
    let loginInfo = result[0]
    loginInfo.login_time = new Date(loginInfo.login_time).format("yyyy-MM-dd hh:mm:ss")
    loginInfo.current_time = new Date(loginInfo.current_time).format("yyyy-MM-dd hh:mm:ss")
    res.send({
      data: loginInfo
    })
  })
})


/* 获取所有登陆信息 */
router.get('/alllogininfo', (req, res) => {
  query("select * from user_login_info", (err, result, fields) => {
    res.send({
      data: result
    })
  })
})
module.exports= router